import { defineStore } from "pinia";
import { apiUserinfo, ApiUserinfo } from "@@/api/module/userInfo";
import { sdkWalletPlatformInfo } from "@@/sdk/tp";
import { toast } from "@@/hooks/vantHooks";
import {
  sdkConnect,
  sdkGetChainId,
  sdkIsEthereum,
  sdkChangeChain,
} from "@@/sdk/web3Eth";
import { funDelay } from "@@/utils/tools/function";
import { apiLogin, ApiLogin } from "@@/api/module/sys";
import { i18n } from "@@/language";
import { logined, resetStore } from "@@/hooks/sysHooks";
import { open } from "@@globalView/invite";

//@ts-ignore
const { t } = i18n.global;
const env = import.meta.env;
const defaultChainId = Number(env.VITE_CHAIN_ID);

export default defineStore("UserinfoStore", {
  //*全局仓库
  state: initState,
  //*全局函数
  actions: {
    /**获取链id */
    async getChainId() {
      if (sdkIsEthereum()) {
        const { data } = await sdkGetChainId();
        window.chainId = Number(data);
      }
    },
    async login(query: AnyObject, count: number = 1): Promise<boolean> {
      console.log("query参数", query);
      /**重试登录次数 */
      const max = 0;
      const loginDelay = () => {
        resetStore();
        if (count > max) return false;
        return funDelay(this.login, [query, count]);
      };
      console.log(`第${count}次尝试登录`);
      // toast.loading(`${t("zhen-zai-lian-jie")}...${count}/${max}`);
      count++;
      let res = false;
      await sdkChangeChain(defaultChainId);
      //* 检查链
      await this.getChainId();
      if (window.chainId != defaultChainId) {
        toast.error(t("qingQieHuanDao") + env.VITE_CHAIN_NAME);
        return loginDelay();
      }
      res = await this.connectEth(query.invit);
      if (res === true) return res;
      return loginDelay();
    },
    /**以太坊钱包连接 */
    async connectEth(invit?: string): Promise<boolean> {
      console.log("连接eth钱包");
      const connectRes = await sdkConnect();
      if (!connectRes.status) {
        toast.error(connectRes.message + ": ethereum");
        return false;
      }
      const [getChainIdRes, { data }] = await Promise.all([
        sdkGetChainId(),
        sdkWalletPlatformInfo(),
      ]);
      if (!getChainIdRes.status) {
        toast.error(`${t("lian-jie-qian-bao-shi-bai")} : thereum`);
        return false;
      }
      /**钱包名称 */
      const walletName = data?.name;
      const loginRes = await this.requestLogin({
        chainId: getChainIdRes.data!,
        nwtworkId: defaultChainId,
        accounts: connectRes.data!,
        invit,
        clientId: "123456789",
        code: "123456789",
        that_wallet_name: walletName || "",
      });
      if (!loginRes) return false;
      return true;
    },
    /**请求登录并储存信息 */
    async requestLogin(params: ApiLogin.Req): Promise<boolean> {
      const { lastLoginInfo } = this;
      //* 如果所有账户信息都相同而且没有邀请码则不请求服务器
      console.log(params);
      if (
        params.accounts == lastLoginInfo?.accounts &&
        params.chainId == lastLoginInfo?.chainId &&
        !params.invit
      ) {
        return logined();
      }
      resetStore();
      const res = await apiLogin(params);
      if (res.code === 10002) {
        setTimeout(open, 1500);
        throw new Error("取消本次重试");
      }
      if (res.code !== 200) return false;
      this.$patch((state) => {
        state.tokenInfo = res.data;
        state.lastLoginInfo = params;
      });
      this.address = lastLoginInfo?.accounts;
      return logined();
    },
    async getUserinfo() {
      const res = await apiUserinfo();
      if (!res) return;
      this.$patch((state) => {
        state.userinfo = res;
        state.address = res.address;
      });
    },
    async getWalletName() {
      const res = await sdkWalletPlatformInfo();
      return (this.walletName = res.data?.name || "WKW user");
    },
  },
  //*计算属性
  getters: {},
  //*仓库数据缓存
  persist: [
    {
      key: "UserinfoStore",
      storage: localStorage, //指定储存位置
    },
  ],
});
/**state类型定义 */
interface UserinfoStore {
  userinfo: ApiUserinfo.Data | undefined;
  tokenInfo: ApiLogin.Data | undefined;
  lastLoginInfo: LastLoginInfo | undefined;
  walletName: string | undefined;
  address: string | undefined;
}
interface LastLoginInfo extends ApiLogin.Req {}

/**初始化pinia */
function initState(): UserinfoStore {
  return {
    walletName: undefined,
    address: undefined,
    userinfo: undefined,
    lastLoginInfo: undefined,
    tokenInfo: undefined,
  };
}
